package com.dongdongshop.controller;

import com.dongdongshop.service.OrderService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;

import java.util.Map;

/*MQ回调事务侦听器
* 事务消息监听器
* */
@RocketMQTransactionListener(txProducerGroup = "UserScoreTable")
public class MQCallbackTransactionListener implements RocketMQLocalTransactionListener {
    @DubboReference
    private OrderService orderService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 1、MQ服务，成功接到事物消息后，执行本方法；
     * 2、处理本地事物，并将本地事物处理结果返回给MQ服务
     *
     * @return COMMIT, ROLLBACK, UNKNOWN;
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        //message,要发送的消息
        String id = message.getHeaders().getId().toString();
        Object payload = message.getPayload();
        System.out.println(payload);
        /*o : 将支付流水号加入数据库中需要的参数*/
        try {
            Map<String,Object> map = (Map<String, Object>) o;
            String out_trade_no = (String) map.get("out_trade_no");
            String trade_no = (String)map.get("trade_no");
            orderService.insertTradeNo(out_trade_no,trade_no);
        }catch (Exception e){
            e.printStackTrace();
            redisTemplate.boundValueOps(id).set("ERROR");
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        /*执行成功,记录一个成功的标签,防止MQ发送失败*/
        redisTemplate.boundValueOps(id).set("SUCCESS");
        return RocketMQLocalTransactionState.COMMIT;
    }
    /**
     * MQ服务 由于网络等原因 未收到 本地事物处理结果，回查本地事物处理结果
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        /*如果MQ发送失败,重试之前先判断之前执行的修改操作是否成功*/
        String id = message.getHeaders().getId().toString();
        /*获取重试之前的事务状态*/
        String status = (String)redisTemplate.boundValueOps(id).get();
        if("SUCCESS".equals(status)){//事务执行成功
            return RocketMQLocalTransactionState.COMMIT;
        }else if ("ERROR".equals(status)){//事务执行失败
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        //未知
        return RocketMQLocalTransactionState.UNKNOWN;
    }
}
